package threadpool;

import java.util.concurrent.*;

public class DynamicThreadPool {

    private ThreadPoolExecutor threadPoolExecutor;

    public DynamicThreadPool(int corePoolSize, int maxPoolSize, long keepAliveTime, TimeUnit unit) {
        threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, unit, new LinkedBlockingQueue<>());
    }

    // 根据当前任务数量调整线程池大小
    public void adjustThreadPoolSize(int currentTaskCount) {
        int currentPoolSize = threadPoolExecutor.getPoolSize();
        int currentActiveCount = threadPoolExecutor.getActiveCount();
        if (currentTaskCount > currentActiveCount && currentPoolSize < threadPoolExecutor.getMaximumPoolSize()) {
            threadPoolExecutor.setCorePoolSize(currentActiveCount);
            threadPoolExecutor.setMaximumPoolSize(threadPoolExecutor.getMaximumPoolSize() + 1);
        }
        if (currentTaskCount < currentActiveCount && currentPoolSize > threadPoolExecutor.getCorePoolSize()) {
            threadPoolExecutor.setMaximumPoolSize(currentActiveCount);
        }
    }

    // 提交任务到线程池
    public Future<?> submitTask(Runnable task) {
        return threadPoolExecutor.submit(task);
    }

    // 关闭线程池
    public void shutdown() {
        threadPoolExecutor.shutdown();
    }

}
